use rust_xlsxwriter::{Workbook, XlsxError}; // 移除 Worksheet
use serde_json::{Map, Value};

pub fn export_excel(
    table_header: Vec<&str>,
    data: Vec<Vec<String>>,
    path: &str,
) -> Result<(), XlsxError> {
    let mut workbook = Workbook::new();

    // 添加工作表
    let worksheet = workbook.add_worksheet(); // 去掉 ?

    for (index, header) in table_header.iter().enumerate() {
        worksheet.write_string(0, index as u16, header.to_string())?;
    }

    for (index, row) in data.iter().enumerate() {
        for (col_index, col) in row.iter().enumerate() {
            // 将 usize 转换为 u32，再转换为 u16，并解引用字符串切片为字符串
            worksheet.write_string((index + 1) as u32, col_index as u16, col.to_string())?;
        }
    }

    // 保存文件
    workbook.save(path)?;

    Ok(())
}

pub fn convert_json_to_table(data: &[Value]) -> Option<(Vec<&str>, Vec<Vec<String>>)> {
    // 1. 提取表头（假设第一个元素是对象）
    let first_obj: &Map<String, Value> = data.first()?.as_object()?;
    let headers: Vec<&str> = first_obj.keys().map(|k| k.as_str()).collect();

    // 2. 提取数据行
    let rows: Vec<Vec<String>> = data
        .iter()
        .filter_map(|value| {
            let obj = value.as_object()?;
            Some(
                headers
                    .iter()
                    .map(|key| match obj.get(*key) {
                        Some(v) => value_to_string(v),
                        None => String::new(), // 缺失字段填空字符串
                    })
                    .collect(),
            )
        })
        .collect();

    Some((headers, rows))
}

/// 将 JSON Value 转换为友好字符串格式
pub fn value_to_string(v: &Value) -> String {
    match v {
        Value::Null => String::new(),
        Value::Bool(b) => b.to_string(),
        Value::Number(n) => n.to_string(),
        Value::String(s) => s.clone(),
        Value::Array(_) => "[Array]".to_string(),
        Value::Object(_) => "{Object}".to_string(),
    }
}
